package com.hiking.cmdchat;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.hiking.cmdchat.adapter.PromptAdapter;
import com.hiking.cmdchat.bean.PromptBean;
import com.hiking.cmdchat.utils.PromptSearchUtils;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;

public class MyEditerView extends LinearLayout {
    @BindView(R.id.input_et)
    EditText editText;
    @BindView(R.id.prompt)
    RecyclerView prompt;
    Context context;
    PromptAdapter promptAdapter;
    ArrayList<PromptBean> datas;

    public MyEditerView(Context context) {
        this(context, null);
    }

    public MyEditerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyEditerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        LayoutInflater.from(context).inflate(R.layout.myediterview, this, true);
        ButterKnife.bind(this);
        initRecycleView();
    }

    @OnClick(R.id.enter)
    void send() {
        if (mSendListener != null) {
            mSendListener.onSendClick(editText.getText().toString());
        }
        editText.setText("");

    }

    @OnTextChanged(value = R.id.input_et, callback = OnTextChanged.Callback.TEXT_CHANGED)
    void onTextChanged(CharSequence s, int start, int before, int count) {
        editText.setSelection(s.length());//将光标移至文字末尾
        refreshPrompts(s);
    }

    private void refreshPrompts(CharSequence s) {
        if (null == datas) return;
        datas.clear();
        datas.addAll(PromptSearchUtils.search(s + ""));
        promptAdapter.notifyDataSetChanged();
    }

    private void initRecycleView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        prompt.setLayoutManager(linearLayoutManager);
        datas = new ArrayList<>();
        promptAdapter = new PromptAdapter(datas);
        promptAdapter.setOnItemClickListener(new PromptAdapter.ItemClickListener() {
            @Override
            public void onItemClick(int position) {
                editText.setText(datas.get(position).getContent());
            }
        });
        prompt.setAdapter(promptAdapter);
    }

    /**
     * 定义一个接口
     */
    public interface SendListener {
        void onSendClick(String data);
    }

    public SendListener mSendListener;

    public void setOnSendListener(SendListener mListener) {
        this.mSendListener = mListener;
    }
}
